package Thread;
//线程安全问题
//加锁解决线程不安全问题
public class ThreadDemo16 {
    private static int count=0;
    public static void main(String[] args) throws InterruptedException {
        Object locker=new Object();
        Thread t1=new Thread(()->{
            for (int i = 0; i < 50000; i++) {
                synchronized (locker){
                    count++;
                }
            }
        });
        Thread t2=new Thread(()->{
            for (int i = 0; i < 50000; i++) {
                synchronized (locker){
                    count++;
                }
            }
        });
        t1.start();
        t2.start();
        // 如果没有这俩 join, 肯定不⾏的. 线程还没⾃增完, 就开始打印了. 很可能打印出来的 count是初始未累加的值0，或者计算过程中的不准确的值
        t1.join();
        t2.join();
        // 预期结果应该是 10w
        System.out.println("count: " + count);

    }
}
